package persistencia;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;



public class PersistirImagen extends Persistir {

	public PersistirImagen() {}
	
	public boolean existeImagen(int id){
		boolean existe = false;
		try {
			Statement consulta = this.getConexion().createStatement();
			ResultSet rs= consulta.executeQuery("SELECT Id FROM Imagen WHERE Id = '"+id+"'");
			existe = rs.next();
			rs.close();
		} catch (Exception e) {
			System.out.println("ERROR EN LA BD");
		}
		
		return existe;
	}
	
	public void addImagen(byte[] byteFoto, String des) {

		try {
			Connection cox = getConexion();
			PreparedStatement ps =	cox.prepareStatement("INSERT INTO Imagen (Foto, Descripcion) VALUES (?,?);");
			ps.setBytes(1, byteFoto);
			ps.setString(2, des);
			ps.executeUpdate();
			ps.close();
		} 
		catch (Exception  e) {
			e.printStackTrace();
		}
	} 
	
	

	
	public Image getImagen(int id){
		Image data = null;
		try {
			Statement consulta = this.getConexion().createStatement();
			ResultSet rs= consulta.executeQuery("SELECT Foto, Descripcion FROM Imagen WHERE Id = '"+id+"'");
			
			if (rs.next()){
				byte[] b = rs.getBytes("Foto");
				data = convertirImagen(b);
			}
			rs.close();
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return data;	
	}
	

	//CONVERTIR UNA IMAGEN GUARDADA EN LA BD A "Image"
	private Image convertirImagen(byte[] bytes) throws IOException{
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpeg");
		ImageReader reader = (ImageReader) readers.next();
		Object source = bis;
		ImageInputStream iis = ImageIO.createImageInputStream(source);
		reader.setInput(iis, true);
		ImageReadParam param = reader.getDefaultReadParam();
		return reader.read(0, param);
	}
	
}
